import { CanActivate, ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common';
import { Observable } from 'rxjs';
import { GqlExecutionContext } from '@nestjs/graphql';
import { ICurrentUserType } from 'src/decorators/current.user';
import { AuthService } from 'src/modules/common/auth/auth.service';
import { UserEntity } from 'src/modules/blog/user/entities/user.entity';
import { RedisUtilsService } from 'src/modules/common/redis-utils/redis-utils.service';
import { UserTokenEntity } from 'src/modules/blog/entities/user_token.entity';
import dayjs from 'dayjs';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private readonly authService: AuthService,
    private readonly redisUtilsService: RedisUtilsService
    ) {}
  async  canActivate(
    context: ExecutionContext,
  ):  Promise<boolean> {
    const ctx = GqlExecutionContext.create(context);
    const token = ctx.getContext().req.headers.token;
    if (token) {
      try {
        const userInfo = await UserTokenEntity.findOne({ where: { token }, select: ['userId', 'username', 'mobile', 'expireTime', 'platform']});
        const isExpire = dayjs().diff(userInfo?.expireTime) <= 0 ? false : true;
        console.log(userInfo, isExpire, '===>', dayjs().diff(userInfo?.expireTime));
        if (userInfo || isExpire) {
          // 将当前账号信息挂载到req上
          ctx.getContext().req.user = userInfo;
          return true;
        } else {
          throw new UnauthorizedException('请重新登录');
        }
        // const tokenObj: ICurrentUserType = this.authService.verifyToken(token);
        // const redisData = await this.redisUtilsService.get(tokenObj.redisTokenKey);
        // console.log(redisData);
        // console.log(tokenObj, 'token中解密的数据');
        // if(Object.is(token, redisData?.token)){
        //       // 数据库查询当前账号是否存在，方式jwt被人破解，传递过来的数据，但是账号表中不存在
        //   // const user = await UserEntity.findOne(tokenObj.id, { select: ['id', 'username'] });
        
        // } else {
        //   throw new UnauthorizedException('请重新登录');
        // }
      } catch (e) {
        throw new UnauthorizedException(e);
      }
    } else {
      throw new UnauthorizedException('你无权方法该接口');
    }
  }
}
